kotlin+mvvm+databinding+recyclerview
今天在跟朋友討論程式碼的時候,他點出我用databing是可以不需要listener的,我稍微修改了一些前兩天的程式碼,也把前兩天的code整合起來
在結合code之前,我實作了一個viewmodelFactor,是用擴展的方式實作
class ViewModelFactory(application: Application) : ViewModelProvider.AndroidViewModelFactory(application)
fun <T : ViewModel> ViewModelStoreOwner.initViewModel(application: Application, viewModel: Class<T>): T = ViewModelProvider(this,
ViewModelFactory(application = application)).get(viewModel)
這邊要繼承AndroidViewModel因為可以引入application
再來是修改過後的activity,adapter,viewmodel
首先是activity
class Activity:AppCompatActivity() {
lateinit var binding: ActivityMainBinding
private val mViewModel by lazy {
initViewModel(application, ViewModel::class.java)
}
private val mAdapter by lazy {
Adapter<Post>(R.layout.item_view,mViewModel)
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
binding = DataBindingUtil.setContentView(this, R.layout.activity_main)
binding.recyclerView.adapter = mAdapter
mViewModel.data.observe(this, Observer { post ->
mAdapter.updateData(post)
})
mViewModel.fetchData()
}
}
adapter
class Adapter<T>(
@LayoutRes val resource: Int,
val viewmodel:ViewModel
) : RecyclerView.Adapter<RecyclerView.ViewHolder>() {
private val data: List<T>
get() = _data.toList()
private val _data: MutableList<T> = mutableListOf()
fun updateData(list: ArrayList<T>){
_data.clear()
_data.addAll(list)
notifyDataSetChanged()
}
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): RecyclerView.ViewHolder {
val layoutInflater = LayoutInflater.from(parent.context)
val binding = DataBindingUtil.inflate<ViewDataBinding>(layoutInflater, resource, parent,false)
return MyViewHolder(binding)
}
override fun getItemCount(): Int {
return data.size
}
override fun onBindViewHolder(holder: RecyclerView.ViewHolder, position: Int) {
if (holder is Adapter<*>.MyViewHolder){
val item = data[position]
if (item != null)
holder.setupData(item)
}
}
inner class MyViewHolder( var binding: ViewDataBinding):RecyclerView.ViewHolder(binding.root){
fun setupData(post: Any){
binding.setVariable(BR.Post, post)
binding.setVariable(BR.viewmodel,viewmodel)
}
}
}
viewmodel
![https://ithelp.ithome.com.tw/upload/images/20210915/20141791zjHci8JfER.jpg](https://ithelp.ithome.com.tw/upload/images/20210915/20141791zjHci8JfER.jpg)```